import React,{ Component } from "react"
export default class Add extends Component{
    constructor(props){
        super(props)
        this.state={
            val:"doing",
            inputval:"doing"
        }
        // this.fun = this.fun.bind(this);
        this.btnAdd = this.btnAdd.bind(this)
        this.keydown = this.keydown.bind(this)
        this.inputWillNull = React.createRef() //利用ref将input框里面的值清空
    }
    fun = (e)=>{
        this.setState({
            inputval:e.target.value
        })
    }
    btnAdd(){
        if(this.state.inputval){
            this.props.addval(this.state.inputval)
            this.setState({
                val:"",
                inputval:""
            })
            this.inputWillNull.current.value=""//ref
        }else{
            alert("不能为空")
        }
    }
    keydown(e){
        // console.log("key")
        if(e.keyCode === 13){
            this.btnAdd()
        }
    }
    render(){
        return (
        <div>
            <input ref={this.inputWillNull} type="text" defaultValue = {this.state.val}  onChange={this.fun.bind(this)} onKeyDown={this.keydown}/>
            <button onClick={this.btnAdd} >添加 </button>
        </div>
        )
    }
}